// 机构详情
import React, { useEffect } from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { Link } from 'react-router-dom';
import { Card, Button, Tabs, Table } from 'antd';
import * as detailApi from '~/apis/institution/detailApi';
import { getConsultColumns, getCaseColumns, getUrlSearch, getDetail } from './pageConfig';
import './index.local.sass';

const { TabPane } = Tabs;

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const setCardTitle = (title: string) => (
  <div className="card-title">
    <span className="title-icon">&nbsp;</span>
    <span>{title}</span>
  </div>
);

const InstitutionDetail = observer(() => {
  const state = useLocalStore(() => (
    {
      loading: false, // 表格加载中
      visibleFlag: false,
      orgId: getUrlSearch('id'), // 机构id
      headLogo: '', // 头像logo
      fileUrlPrefix: '', // 文件地址前缀
      relateCaseData: [], // 相关案例表格数据
      startProjectInfo: [], // 关注项目表格
      institutionInfo: null as any, // 机构详情
    }
  ));

  // 根据id 查询咨询项目 表格数据
  const getConsultProjectInfo = () => {
    state.loading = true;

    detailApi.getConsultProjectInfo({ orgId: state.orgId }).then((res) => {
      state.startProjectInfo = res.data ? res.data : [];
    }).finally(() => {
      state.loading = false;
    });
  };

  // 根据id 查询机构详情
  const getInstitutionInfo = () => {
    detailApi.getInstitutionInfo({ id: state.orgId }).then((res) => {
      state.fileUrlPrefix = res.file_prefix; // 文件地址前缀
      if (res.file_prefix && res.data && res.data.organizationLogo) {
        state.headLogo = `${res.file_prefix as string}${res.data.organizationLogo as string}`; // 头像logo
      }

      const institutionInfo = res.data ? res.data : null;
      if (institutionInfo?.followIndustryName && institutionInfo.followIndustryName.length > 0) {
        institutionInfo.followIndustryName = institutionInfo.followIndustryName.join(',');
      }
      if (institutionInfo?.followCountryName && institutionInfo.followCountryName.length > 0) {
        institutionInfo.followCountryName = institutionInfo.followCountryName.join(',');
      }

      state.institutionInfo = getDetail(res.data);
    });
  };

  // 下载文件
  const handleViewFile = (param: number | string) => {
    if (param) {
      window.location.href = `${state.fileUrlPrefix}${param}`;
    }
  };

  // 根据id 查询机构详情
  useEffect(() => {
    getInstitutionInfo();
    getConsultProjectInfo();
  }, []);

  const consultColumns = getConsultColumns({ handleViewFile });

  const caseColumns = getCaseColumns({ handleViewFile });

  // 表格属性
  const consulTableOption: any = {
    dataSource: state.startProjectInfo || [],
    columns: consultColumns,
    pagination: false,
    loading: state.loading,
    // bordered: true,
    size: 'small',
  };

  const caseTableOption: any = {
    dataSource: state.relateCaseData || [],
    columns: caseColumns,
    pagination: false,
    loading: state.loading,
    // bordered: true,
    size: 'small',
  };

  // 根据id 查询关注项目 表格数据
  const getStartProjectInfo = () => {
    state.loading = true;

    detailApi.getStartProjectInfo({ orgId: state.orgId }).then((res) => {
      state.startProjectInfo = res.data ? res.data : [];
    }).finally(() => {
      state.loading = false;
    });
  };

  // 根据id 查询相关案例 表格数据
  const getRelateCaseInfo = () => {
    state.loading = true;

    detailApi.getRelateCaseInfo({ orgId: state.orgId }).then((res) => {
      state.relateCaseData = res.data ? res.data : [];
    }).finally(() => {
      state.loading = false;
    });
  };

  // 切换tab
  const changeTab = (key: string) => {
    if (key === '1') {
      getConsultProjectInfo();
    } else if (key === '2') {
      getStartProjectInfo();
    } else if (key === '3') {
      getRelateCaseInfo();
    }
  };

  return (
    <div>
      <Card
        {...cardConfig}
        title={
          setCardTitle('Institution Infomation')
        }
        extra={
          <div>
            <Link to={`/institution/edit?id=${state.orgId as string}`}>
              <Button className="button-style">Edit</Button>
            </Link>
          </div>
        }
        className="info-card"
      >

        <ul className="detail-container">
          {
            state.institutionInfo ? state.institutionInfo.map((item: any, index: number) => {
              if (item.isTitle) {
                return (
                  <li className="detail-content" key={index}>
                    <p className="content-left">
                      <span className="avatar bg-gray-100">
                        <img className="avatar-img" src={state.headLogo}/>
                      </span>
                    </p>
                    <p className="content-right right-add">{item.value}</p>
                  </li>
                );
              }
              return (
                <li className="detail-content" key={index}>
                  <p className="content-left">{item.key}</p>
                  <p className="content-right">{item.value}</p>
                </li>
              );
            }) : <></>
          }
        </ul>
      </Card>

      <Card
        {...cardConfig}
        className="table-card"
      >
        <Tabs defaultActiveKey="1" onChange={(value: string) => {
          changeTab(value);
        }}>
          <TabPane tab="Case description" key="1">
            <Table
              rowKey={(record: any, index: number) => `complete${record.id as string}${index}`}
              {...consulTableOption}
            />
          </TabPane>
          <TabPane tab="Start Project" key="2">
            <Table
              rowKey={(record: any, index: number) => `complete${record.id as string}${index}`}
              {...consulTableOption}
            />
          </TabPane>
          <TabPane tab="Related Cases" key="3">
            <Table
              rowKey={(record: any, index: number) => `complete${record.id as string}${index}`}
              {...caseTableOption}
            />
          </TabPane>
        </Tabs>
      </Card>

    </div>
  );
});
export default InstitutionDetail;
